class Team {
    constructor(name) {
        this.name = name; // 队名
        this.played = 0; // 已比赛场数
        this.won = 0; // 赢的场数
        this.drawn = 0; // 平的场数
        this.lost = 0; // 负的场数
        this.goalsScored = 0; // 进球数
        this.goalsConceded = 0; // 失球数
        this.points = 0; // 积分
    }

    // 更新球队数据
    update(matchGoalsScored, matchGoalsConceded) {
        this.played += 1;
        this.goalsScored += matchGoalsScored;
        this.goalsConceded += matchGoalsConceded;

        if (matchGoalsScored > matchGoalsConceded) {
            this.won += 1;
            this.points += 3;
        } else if (matchGoalsScored === matchGoalsConceded) {
            this.drawn += 1;
            this.points += 1;
        } else {
            this.lost += 1;
        }
    }
}

// 比赛数据录入并更新积分表
function updateStandings(teams, matchResult) {
    const { homeTeam, awayTeam, homeGoals, awayGoals } = matchResult;

    // 查找主客队
    const home = teams.find(team => team.name === homeTeam);
    const away = teams.find(team => team.name === awayTeam);

    if (!home || !away) {
        console.error("未找到对应球队！");
        return;
    }

    // 更新主客队数据
    home.update(homeGoals, awayGoals);
    away.update(awayGoals, homeGoals);

    // 排序积分表
    teams.sort((a, b) => {
        if (b.points !== a.points) return b.points - a.points;
        const aGoalDifference = a.goalsScored - a.goalsConceded;
        const bGoalDifference = b.goalsScored - b.goalsConceded;
        if (bGoalDifference !== aGoalDifference) return bGoalDifference - aGoalDifference;
        if (b.goalsScored !== a.goalsScored) return b.goalsScored - a.goalsScored;
        return 0; // 积分、净胜球和进球数都相等
    });
}

// 打印积分表
function printStandings(teams) {
    console.log("排名\t队名\t比赛\t胜\t平\t负\t进球\t失球\t积分");
    teams.forEach((team, index) => {
        console.log(
            `${index + 1}\t${team.name}\t${team.played}\t${team.won}\t${team.drawn}\t${team.lost}\t${team.goalsScored}\t${team.goalsConceded}\t${team.points}`
        );
    });
}

const teams = [
    new Team("TeamA"),
    new Team("TeamB"),
    new Team("TeamC"),
    new Team("TeamD")
];

// 输入比赛结果
const matchResults = [
    { homeTeam: "TeamA", awayTeam: "TeamB", homeGoals: 2, awayGoals: 1 },
    { homeTeam: "TeamC", awayTeam: "TeamD", homeGoals: 1, awayGoals: 1 },
    { homeTeam: "TeamA", awayTeam: "TeamC", homeGoals: 3, awayGoals: 0 },
    { homeTeam: "TeamB", awayTeam: "TeamD", homeGoals: 0, awayGoals: 2 }
];

// 更新积分表
matchResults.forEach(matchResult => updateStandings(teams, matchResult));

// 打印最新积分表
printStandings(teams);
